package com.yl.immodule.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.camera.base.Log.YLogImpl;
import com.camera.base.bean.DownloadState;
import com.camera.base.inerface.DownloadCallback;
import com.camera.base.inerface.YLWebrtcInterface;
import com.camera.base.net.api.ApiServiceEntryPoint;
import com.camera.base.net.listener.DownLoadInterface;
import com.camera.base.net.listener.NetInterface;
import com.camera.base.net.response.AuthResponse;
import com.camera.base.util.FileUtil;
import com.camera.base.util.StorageUtil;
import com.camera.routemodule.RouterPath;
import com.camera.routemodule.routeinterface.RouterUtil;
import com.hm.poc.http.HttpCallback;
import com.hm.poc.http.HttpSenderManager;
import com.yl.immodule.R;
import com.hm.poc.chat.ChatMessageStatus;
import com.unionbroad.greendao.ChatMessage;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;
import dagger.hilt.android.EntryPointAccessors;
import dagger.hilt.android.HiltAndroidApp;

//@AndroidEntryPoint // <-- 正确的注解
public class VideoFileCellLayout extends RelativeLayout implements View.OnClickListener, View.OnLongClickListener {
    private static final String TAG = "VideoFileCellLayout";
//    @Inject
//    @Nullable
    private DownLoadInterface downLoadInterface;
    private ImageView thumbnailView;
    private ImageView playButton;
    private TextView durationText;
    private ProgressBar progressBar;
    private String localSource;
    private String httpSource;
    private String id;
    private boolean isOut;
    private ChatMessage message;
    private long duration = 0;
    private boolean isDownloading = false;
    private void initDownLoadInterface(Context context) {
        try {
            ApiServiceEntryPoint entryPoint = EntryPointAccessors.fromApplication(
                    context.getApplicationContext(),
                    ApiServiceEntryPoint.class
            );
            downLoadInterface = entryPoint.getDownloadInterface();
            Log.d(TAG, "DownLoadInterface 初始化成功  downLoadInterface示例是否存在"+ (downLoadInterface == null));

        } catch (Exception e) {
            Log.e(TAG, "DownLoadInterface 初始化失败: " + e.getMessage(), e);
        }
    }
    public VideoFileCellLayout(Context context, AttributeSet attrs) {

        super(context, attrs);
        Log.e(TAG, "VideoFileCellLayout:1 " );
        initDownLoadInterface(context);
        setOnClickListener(this);
        setOnLongClickListener(this);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        thumbnailView = findViewById(R.id.video_thumbnail);
        playButton = findViewById(R.id.play_button);
        durationText = findViewById(R.id.video_duration);
        progressBar = findViewById(R.id.video_progress);
    }

    public void bindData(ChatMessage message) {
        Log.e(TAG, "bindData:1 " );
        this.message = message;
        localSource = message.getLocalFile();
        httpSource = message.getHttpFile();
        id = message.getId();
        isOut = message.getIs_out();
        duration = message.getDuration() != null ? message.getDuration() : 0;

        // 设置视频时长
        durationText.setText(formatDuration(duration));

        // 设置下载进度
        int progress = message.getUpdown_progress();
        if (progress > 0 && progress < 100) {
            progressBar.setVisibility(View.VISIBLE);
            progressBar.setProgress(progress);
            isDownloading = true;
        } else {
            progressBar.setVisibility(View.GONE);
            isDownloading = false;
        }

        // 加载缩略图
        loadThumbnail();
        
        // 更新播放/下载按钮状态
        updatePlayDownloadButton();
    }

    private void updatePlayDownloadButton() {
        // 如果有本地文件，显示播放图标
        Log.e(TAG, "updatePlayDownloadButton: "+localSource  +"-" + httpSource);
        if (!TextUtils.isEmpty(localSource) && new File(localSource).exists()) {
            playButton.setImageResource(R.drawable.ic_play_circle);
        } 
        // 如果有网络地址但没有本地地址，显示下载图标
        else if (!TextUtils.isEmpty(httpSource) && (TextUtils.isEmpty(localSource) || !new File(localSource).exists())) {
            // 检查是否正在下载中
            if (isDownloading) {
                playButton.setImageResource(R.drawable.ic_downloading);
            } else {
                playButton.setImageResource(R.drawable.ic_download);
            }
        }
        // 其他情况也显示播放图标，点击时会提示错误
        else {
            playButton.setImageResource(R.drawable.ic_play_circle);
        }
    }

    private void loadThumbnail() {
        // 优先加载本地视频的缩略图
        if (!TextUtils.isEmpty(localSource)) {
            File file = new File(localSource);
            if (file.exists()) {
                // 使用AsyncTask异步生成缩略图，避免阻塞UI线程
                new GenerateThumbnailTask().execute(localSource);
                return;
            }
        }

        // 本地文件不存在，尝试加载网络视频缩略图或显示默认图片
        if (!TextUtils.isEmpty(httpSource)) {
            // 可以尝试从网络加载缩略图，或者显示默认缩略图
            Glide.with(getContext())
                    .load(R.drawable.ic_video_placeholder)
                    .into(thumbnailView);
        } else {
            // 既没有本地也没有网络地址，显示默认图片
            Glide.with(getContext())
                    .load(R.drawable.ic_video_placeholder)
                    .into(thumbnailView);
        }
    }

    private class GenerateThumbnailTask extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... paths) {
            if (paths.length == 0) return null;
            
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            try {
                retriever.setDataSource(paths[0]);
                // 获取视频的中间帧作为缩略图
                return retriever.getFrameAtTime(1000000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
            } catch (Exception e) {
                Log.e(TAG, "Failed to generate thumbnail: " + e.getMessage() +"   path:"+ paths[0]);
                return null;
            } finally {
                try {
                    retriever.release();
                } catch (Exception e) {
                    Log.e(TAG, "Error releasing retriever: " + e.getMessage());
                }
            }
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                thumbnailView.setImageBitmap(bitmap);
            } else {
                // 生成缩略图失败，显示默认图片
                Glide.with(getContext())
                        .load(R.drawable.ic_video_placeholder)
                        .into(thumbnailView);
            }
        }
    }

    private String formatDuration(long seconds) {
        if (seconds <= 0) {
            return "00:00";
        }
        
        long minutes = TimeUnit.SECONDS.toMinutes(seconds);
        seconds = seconds - TimeUnit.MINUTES.toSeconds(minutes);
        
        return String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
    }
    /**
     * 创建输出文件路径
     */
    private String createOutputVideoPath(){
        if (FileUtil.INSTANCE.getBaseVideoIMPath() != null){
            SimpleDateFormat timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
            File file = new File(FileUtil.INSTANCE.getBaseVideoIMPath());
            if (!file.exists()) {
                file.mkdirs();
            }
            return new File(FileUtil.INSTANCE.getBaseVideoIMPath(), "VID_"+timeStamp.format(new Date())+"_"+ UUID.randomUUID()+".mp4").getAbsolutePath();
        }
        return null;
    }
    // 下载视频的方法
    private void downloadVideo() {
        if (TextUtils.isEmpty(httpSource)) {
            Toast.makeText(getContext(), "视频地址为空，无法下载", Toast.LENGTH_SHORT).show();
            return;
        }
        YLogImpl.i(TAG,"downloadVideo "+localSource);
        // 如果localSource为空，则生成一个本地存储路径
        if (TextUtils.isEmpty(localSource)) {
            // 确保视频下载目录存在
            localSource = createOutputVideoPath();
            YLogImpl.i(TAG,"downloadVideo 创建本地文件:"+localSource);
            if (localSource == null) {
                Toast.makeText(getContext(), "无法创建下载目录", Toast.LENGTH_SHORT).show();
                return;
            }
            
//            // 使用消息ID或生成一个随机名称作为文件名
//            String fileName = TextUtils.isEmpty(id) ?
//                    "video_" + UUID.randomUUID().toString() + ".mp4" :
//                    "video_" + id + ".mp4";
            
//            localSource = videoDir + File.separator + fileName;
            
            // 更新消息的本地文件路径
            message.setLocalFile(localSource);
            // 这里可能需要保存更新后的消息到数据库，取决于你的实现
        }

        // 显示进度条
        progressBar.setVisibility(View.VISIBLE);
        progressBar.setProgress(0);
        isDownloading = true;
        
        // 更新按钮状态为下载中
        playButton.setImageResource(R.drawable.ic_downloading);
        YLogImpl.i(TAG,"downloadVideo 开始下载");
        // 使用RouterUtil获取下载服务实现
        downLoadInterface.startDownload(httpSource + "?authorization=" + HttpSenderManager.INSTANCE.getToken(), localSource, new DownloadCallback() {
            @Override
            public void onProgress(final int progress) {
                YLogImpl.i(TAG,"downloadVideo progress："+progress);
                post(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setProgress(progress);
                        message.setUpdown_progress(progress);
                        // 这里可能需要保存更新后的消息到数据库，取决于你的实现
                    }
                });
            }

            @Override
            public void onComplete() {
                YLogImpl.i(TAG,"downloadVideo onComplete");
                post(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setVisibility(View.GONE);
                        message.setUpdown_progress(100);
                        isDownloading = false;
                        // 下载完成后更新按钮为播放图标
                        playButton.setImageResource(R.drawable.ic_play_circle);
                        Toast.makeText(getContext(), "视频下载完成", Toast.LENGTH_SHORT).show();
                        
                        // 加载本地缩略图
                        new GenerateThumbnailTask().execute(localSource);
                        
                        // 这里可能需要保存更新后的消息到数据库，取决于你的实现
                    }
                });
            }

            @Override
            public void onFailure(final String error) {
                YLogImpl.i(TAG,"downloadVideo onFailure");
                post(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setVisibility(View.GONE);
                        message.setUpdown_progress(0);
                        isDownloading = false;
                        // 下载失败后恢复下载图标
                        playButton.setImageResource(R.drawable.ic_download);
                        Toast.makeText(getContext(), "视频下载失败: " + error, Toast.LENGTH_SHORT).show();
                        
                        // 这里可能需要保存更新后的消息到数据库，取决于你的实现
                    }
                });
            }

            @Override
            public void onCancel() {
                YLogImpl.i(TAG,"downloadVideo onCancel");
                post(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setVisibility(View.GONE);
                        message.setUpdown_progress(0);
                        isDownloading = false;
                        playButton.setImageResource(R.drawable.ic_download);
                        
                        // 这里可能需要保存更新后的消息到数据库，取决于你的实现
                    }
                });
            }

            @Override
            public void onPause() {
                // 暂停下载的处理，如有需要
            }

            @Override
            public void onResume() {
                // 恢复下载的处理，如有需要
            }
        });
    }

    @Override
    public void onClick(View v) {
        // 修改消息状态为已读
        if (message.getMsg_status() == ChatMessageStatus.Chat.UNREAD) {
            // 调用标记为已读的方法，参考AudioFileCellLayout
            // ICPRtcManager.getsInstance().markMessageAsRead(message);
        }

        // 如果本地文件存在，直接播放
        if (!TextUtils.isEmpty(localSource)) {
            File file = new File(localSource);
            if (file.exists()) {
                // 使用ARouter导航到媒体播放器
                ARouter.getInstance()
                        .build(RouterPath.path.mediaplay_activity)
                        .withString("path", localSource)
                        .withTransition(com.camera.base.R.anim.slide_in_right, com.camera.base.R.anim.slide_out_left)
                        .navigation();
                return;
            }
        }
        YLogImpl.i(TAG,"本地文件不存在  远程地址:"+httpSource);
        // 如果本地文件不存在，但有网络地址，尝试下载或播放
        if (!TextUtils.isEmpty(httpSource)) {
            // 检查下载状态
            if (isDownloading) {
                Toast.makeText(getContext(), "视频下载中，请稍候", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 检查是否有本地文件路径但文件不存在，可能是下载失败或者文件被删除
            if (!TextUtils.isEmpty(localSource) && !new File(localSource).exists()) {
                // 重新下载
                YLogImpl.i(TAG,"检查是否有本地文件路径但文件不存在，可能是下载失败或者文件被删除"+localSource);
                downloadVideo();
                return;
            }
            
            // 检查网络地址但没有本地地址的情况，提示用户下载
            if (TextUtils.isEmpty(localSource) || !new File(localSource).exists()) {
                // 提示用户是否下载视频
                YLogImpl.i(TAG,"开始下载");
                Toast.makeText(getContext(), "开始下载视频", Toast.LENGTH_SHORT).show();
                downloadVideo();
                return;
            }
            
            // 其他情况，尝试直接使用网络地址播放
            ARouter.getInstance()
                    .build(RouterPath.path.mediaplay_activity)
                    .withString("path", httpSource)
                    .withTransition(com.camera.base.R.anim.slide_in_right, com.camera.base.R.anim.slide_out_left)
                    .navigation();
        } else {
            Toast.makeText(getContext(), "视频文件不存在", Toast.LENGTH_SHORT).show();
        }

        // 调用父容器的点击事件
        ((ViewGroup) getParent()).performClick();
    }

    @Override
    public boolean onLongClick(View v) {
        // 转发给父容器，处理长按菜单
        ((ViewGroup) getParent()).performLongClick();
        return true;
    }
} 